/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author jefoutta
 */
import java.util.*;

public class Source {
    public static int [][] vectors;
    public int val;
    protected ArrayList<Connection> outputChannels;
    public String name;
    public int pathCount;

    public Source(String tname){
        this.name = tname;
        outputChannels = new ArrayList();
        
    }

    public void setVal(int tval){
        val = tval;
    }

    public void setSwitch(){
        if(val == 0)
            val = 1;
        else
            if(val == 1)
                val = 0;
    }

    public void setOutputChannel(Connection connection){
        this.outputChannels.add(connection);
        pathCount++;
    }

    public void sensitize(){
        this.val = 2;
        if(this.outputChannels.size() > 1){
            for(int i = 0; i < this.outputChannels.size(); i++){
                if((this.outputChannels.size()-this.pathCount) != i)
                    this.outputChannels.get(i).getDestinyGate().copyVal(2, this.outputChannels.get(i).getInputIndex());
            }
            this.outputChannels.get(this.outputChannels.size()-this.pathCount).getDestinyGate().sensitize(this.outputChannels.get(this.outputChannels.size()-this.pathCount).getInputIndex());
            
        }else{
            this.outputChannels.get(0).getDestinyGate().sensitize(this.outputChannels.get(0).getInputIndex());
        }
        this.pathCount--;
    }

    public void propagateOut(int tval){
        this.val = tval;
        System.out.println("entro a propagateOut " + this.name);
        for(int i = 0; i < this.outputChannels.size(); i++){
            if((this.outputChannels.get(i).getDestinyGate().getInput(this.outputChannels.get(i).getInputIndex()) == -1)||(this.outputChannels.get(i).getDestinyGate().getInput(this.outputChannels.get(i).getInputIndex()) == tval))
                this.outputChannels.get(i).getDestinyGate().copyVal(tval, this.outputChannels.get(i).getInputIndex());
            else {
                this.outputChannels.get(i).getDestinyGate().setError(true);
            }
        }
    }

    public void reset(){
        this.val = -1;
    }

    public void incBack(){
        this.pathCount++;
    }

    public String toString(){
        String s = "";
        for(int i = 0; i < this.outputChannels.size(); i++){
            s = s + " "+this.outputChannels.get(i).getDestinyGate().getName();
        }
        return s;
    }
}
